#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os, sys, signal
import asyncore, asynchat, socket, threading, time

HOST = "127.0.0.1"
PORT = 54344

def DEBUG(format, *args) : print format % args

will_stop = False

def signal_stop( signo, frame ) :
    global  will_stop
    DEBUG( "SERVER catch #%d signal, would stop.", signo )
    will_stop = True
    return
    # signal_stop

class echo_server(threading.Thread):

    def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((HOST, PORT))
        DEBUG('SERVER listening on %s:%d ...', HOST, PORT)
        sock.listen(1)
        conn, client = sock.accept()
        DEBUG('SERVER accept client %s', client)
        buffer = ""
        while "\n" not in buffer:
            data = conn.recv(10)
            if not data:
                break
            buffer = buffer + data
        DEBUG('SERVER echo: %s', buffer)
        while buffer:
            n = conn.send(buffer)
            buffer = buffer[n:]
        DEBUG('SERVER will close connection...')
        conn.close()
        sock.close()

def main():
    # mask signal
    signal.signal( signal.SIGTERM, signal_stop )
    if 'posix' == os.name :
        signal.signal( signal.SIGQUIT, signal_stop )

    s = echo_server()
    try :
        s.start()
        s.join()
    except :
        DEBUG( "SERVER interrupt : %s", `sys.exc_info()[1]` )

if __name__ == '__main__' :
    main()
    sys.exit(0)
